﻿/**************************************************************
 * 
 * 唯一标识：eaea1872-0613-47b2-8d58-e1da69b8a2fd
 * 命名空间：Sgr.Data.DatabaseTranslators
 * 创建时间：2024/6/20 20:25:31
 * 机器名称：DESKTOP-HJ4OAG9
 * 创建者：CocoYuan
 * 电子邮箱：fengqinhua2016@163.com
 * 描述：
 * 
 **************************************************************/

using Sgr.Exceptions;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sgr.Data.DatabaseTranslators
{
    public class DefaultDatabaseTranslatorFactory : IDatabaseTranslatorFactory
    {
        private readonly IEnumerable<IDbProviderFactoryBuilder> _builders;

        public DefaultDatabaseTranslatorFactory(IEnumerable<IDbProviderFactoryBuilder> builders)
        {
            _builders = builders;
        }

        public IDatabaseTranslator CreateTranslator(DatabaseType dataBaseType)
        {
            IDatabaseTranslator databaseTranslator;

            switch (dataBaseType)
            {
                case DatabaseType.Oracle:
                    databaseTranslator = new OracleTranslator(getDbProviderFactory(dataBaseType));
                    break;
                case DatabaseType.SQLite:
                    databaseTranslator = new SqliteTranslator(getDbProviderFactory(dataBaseType));
                    break;
                case DatabaseType.SqlServer:
                    databaseTranslator = new SqlServerTranslator(getDbProviderFactory(dataBaseType));
                    break;
                case DatabaseType.MySql:
                    databaseTranslator = new MySQLTranslator(getDbProviderFactory(dataBaseType));
                    break;
                case DatabaseType.PostgreSql:
                    databaseTranslator = new PostgreSqlTranslator(getDbProviderFactory(dataBaseType));
                    break;
                case DatabaseType.DB2:
                    databaseTranslator = new DB2Translator(getDbProviderFactory(dataBaseType));
                    break;
                default:
                    throw new ArgumentException("未定的类型 {dataBaseType}");
            }

            return databaseTranslator;
        }

        private DbProviderFactory getDbProviderFactory(DatabaseType dataBaseType)
        {
            IDbProviderFactoryBuilder builder = _builders.FirstOrDefault(f => f.DatabaseType == dataBaseType) ?? throw new BusinessException($"未注册 {dataBaseType} 对应的 IDbProviderFactory");
            DbProviderFactory factory = builder.GetDbProviderFactory();
            return factory;
        }
    }
}
